<!-- 注册页面 -->
<template>
  <div class="register">
    <div class="portrait">
      <img :src="PORTRAIT" alt="头像">
    </div>
    <form autocomplete="off" class="info">
      <input type="number" placeholder="请输入手机号" class="info-item" v-model="number">
      <input type="password" placeholder="请输入密码" class="info-item" v-model="password">
      <input type="password" placeholder="确认密码" class="info-item" v-model="confirm">
      <button class="info-item" @click.prevent="submit">注册</button>
    </form>
    <div class="login">
      <router-link to="/login">
        已有账号去登陆
      </router-link>
    </div>
  </div>
  <Transition>
    <Toast v-show="show" :message="toastMessage"></Toast>
  </Transition>
</template>
<script>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { PORTRAIT } from '@/api/interface';
import { post } from '@/utils/request'
import { REGISTER } from '@/api/interface';
import Toast, { useToast } from '@/components/toast';
// 提交用户信息
const useSubmit = (router, showToast) => {
  const number = ref('');
  const password = ref('');
  const confirm = ref('');
  const submit = async () => {
    // 手机号为空
    if (!number.value.toString().trim()) {
      showToast('手机号不能为空');
      return;
    }
    // 密码为空
    if (!password.value.trim()) {
      showToast('密码不能为空');
      return;
    }
    // 密码确认
    if (password.value !== confirm.value) {
      password.value = confirm.value = '';
      showToast('密码不一致,请重新输入');
      return;
    }
    // 发送请求
    try {
      const result = await post(REGISTER, { username: number.value, password: password.value });
      if (result.errno === 0) {
        localStorage.username = number.value;
        router.push({ name: 'login' });
      } else {
        showToast('登录失败');
      }
    } catch (error) {
      console.log(error);
    }
  }
  return { number, password, confirm, submit };
}
//composition
export default {
  name: 'login',
  components: { Toast },
  setup() {
    const router = useRouter();
    const { show, toastMessage, showToast } = useToast();
    const { number, password, confirm, submit } = useSubmit(router, showToast)
    return { show, toastMessage, PORTRAIT, number, password, confirm, submit }
  }
}
</script>
<style scoped lang="scss">
@import '@/styles/theme.scss';
@import '@/styles/mixin.scss';

.register {
  padding-top: 32vw;
}

.portrait {
  @include login-portrait;
}

.info {
  @include login-info;
}

.login {
  @include login-text;
}

// 过渡
.v-enter-from,
.v-leave-to {
  opacity: 0;
}

.v-enter-active,
.v-leave-active {
  transition: opacity .5s;
}
</style>